package producerConsumer;

/**
 * @program: javase
 * @description: 生产者消费者问题--synchronized版
 * @author: lld
 * @create: 2021-04-17 20:21
 **/
public class SyncVersion {
    public static void main(String[] args) {
        Data number = new Data();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    number.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    number.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    number.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    number.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

/**
 * @Description: 不能使用if判断，防止虚假唤醒，必须使用while (num!=0)
 * @Param:
 * @return:
 **/
class Data {
    public int num = 0;

    //    判断等待，业务，唤醒
//    +1方法
    public synchronized void increment() throws InterruptedException {
        //等待 被消费
        while (num != 0) this.wait();
        num++;
        System.out.println(Thread.currentThread().getName() + ">>" + num);
//        唤醒 消费
        this.notify();
    }

    //    -1方法
    public synchronized void decrement() throws InterruptedException {
        //等待 生产
        while (num == 0) this.wait();
        num--;
        System.out.println(Thread.currentThread().getName() + ">>" + num);
//        唤醒
        this.notify();
    }
}
